<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item label="数据源" prop="datasourceId">
        <el-select
          v-model="datasourceId"
          placeholder="请选择数据源"
          clearable
          size="small"
          style="width: 240px"
          @change="changeDb"
        >
          <el-option
            v-for="datasource in datasourceList"
            :key="datasource.id"
            :label="datasource.datasourceName"
            :value="datasource.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据表" prop="tablenameAliasId">
        <el-select
          v-model="queryParams.tablenameAliasId"
          placeholder="请选择数据表"
          clearable
          size="small"
          style="width: 240px"
          @change="changeTable"
        >
          <el-option
            v-for="table in tableList"
            :key="table.id"
            :label="table.tableNameAlias"
            :value="table.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-download" size="small" v-if="showSync" @click="handleSync">同步
        </el-button>
        <el-button icon="el-icon-refresh" size="small" @click="handleRefresh">刷新</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="small" @click="handleInject">生成指标</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="colList"
      row-key="id"
      border>
      <!--      <el-table-column type="selection" width="40" align="center" />-->
      <el-table-column prop="columnName" label="字段名" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="dataType" label="数据类型" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="columnAlias" label="字段别名" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="columnDesc" label="字段说明" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="isquota" label="指标列" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isquota"
            active-value="1"
            inactive-value="0"
            @change="handleQuotaChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="isdimension" label="维度列" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isdimension"
            active-value="1"
            inactive-value="0"
            @change="handleDimChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="80">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
          >修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-form-item label="字段别名" prop="columnAlias">
            <el-input v-model="form.columnAlias" placeholder="请输入数据表别名"></el-input>
          </el-form-item>
          <el-form-item label="字段说明" prop="columnDesc">
            <el-input type="textarea" v-model="form.columnDesc"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="指标">
              <el-switch
                v-model="form.isquota"
                active-value="1"
                inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维度">
              <el-switch
                v-model="form.isdimension"
                active-value="1"
                inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="维度详情" v-if="openDetail" :visible.sync="openDetail" width="900px" append-to-body>
      <DetailValue
        ref="detailValue"
        :datasourceId="datasourceId"
        :colnameAliasId="colnameAliasId"
        :columnAlias="columnAlias"
      />
    </el-dialog>
    <el-dialog title="添加指标" :visible.sync="openQuota" width="550px" append-to-body>
      <el-form ref="form"
               :model="quotaForm"
               :rules="rules"
               v-loading="setLoading"
               label-width="80px">
        <el-form-item label="主题域:">
          <el-select v-model="quotaForm.zoneId" value-key="type" placeholder="请选择主题域" @change="changeZone"
                     style="width: 100%">
            <el-option
              v-for="zone in zoneList"
              :key="zone.id"
              :label="zone.zoneTitle"
              :value="zone.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主题集:">
          <select-tree v-model="quotaForm.themeSetId" :options="setList" :props="defaultProps"/>
        </el-form-item>
        <el-form-item label="名称:">
          <el-input v-model="quotaForm.name" placeholder="请输入指标名称" :readonly="readOnly"/>
        </el-form-item>
        <el-form-item label="简称:">
          <el-input v-model="quotaForm.uname" placeholder="请输入指标简称"/>
        </el-form-item>
        <el-form-item label="注释:">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="quotaForm.description">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelQuota">取 消</el-button>
        <el-button type="primary" @click="submitQuotaForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDatasource } from '@/api/metadata/datasource'
import { getTableAlias, listTableAlias } from '@/api/metadata/tablealias'
import { listColAlias, updateColAlias, getColAlias, syncCol } from '@/api/metadata/colalias'
import { listZone } from '@/api/quota/theme_zone/zone'
import { getThemeSetTree } from '@/api/quota/theme_zone/set'
import { addQuota, injectQuotaValue } from '@/api/quota/define/define'
import DetailValue from '../dimensionDetail/detail'
import SelectTree from '@/components/Widgets/SelectTree'
import Cookies from 'js-cookie'

export default {
  name: 'ColAlias',
  components: { DetailValue, SelectTree },
  data() {
    return {
      // 遮罩层
      loading: false,
      setLoading: false,
      title: '',
      open: false,
      openDetail: false,
      openQuota: false,
      total: 0,
      showSync: false,
      showDetail: false,
      readOnly: true,
      datasourceId: undefined,
      columnAlias: undefined,
      colnameAliasId: undefined,
      setTitle: undefined,
      tableName: undefined,
      row: undefined,
      datasourceList: [],
      tableList: [],
      colList: [],
      zoneList: [],
      setList: [],
      queryParams: {
        current: 1,
        size: 10,
        tablenameAliasId: undefined
      },
      form: {},
      quotaForm: {
        name: undefined
      },
      rules: {
        columnAlias: [
          { max: 50, message: '最大长度为50个字符', trigger: 'blur' }
        ],
        columnDesc: [
          { max: 500, message: '最大长度为500个字符', trigger: 'blur' }
        ]
      },
      defaultProps: {
        parent: 'parentId',   // 父级唯一标识
        value: 'id',          // 唯一标识
        label: 'setTitle',       // 标签显示
        children: 'children' // 子级
      }
    }
  },
  created() {
    listDatasource({ current: 1, size: 10000 }).then(response => {
      this.datasourceList = response.data.records
    })
    listZone({ pageNum: 1, pageSize: 10000 }).then((response) => {
      if (response.code === 0) {
        this.zoneList = response.data.list
      }
    })

  },
  methods: {
    handleRefresh() {
      this.queryParams.current = 1
      this.getList()
    },
    handleSync() {
      getTableAlias(this.queryParams.tablenameAliasId).then(response => {
        if (response.code === 0) {
          let table = response.data
          this.loading = true
          syncCol(table).then(response => {
            this.loading = false
            if (response.code === 0) {
              this.msgSuccess('同步成功')
              this.getList()
            } else {
              this.msgError(response.msg)
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.reset()
      let id = row.id
      this.row = row
      getColAlias(id).then(response => {
        this.form = response.data
        this.open = true
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {

          updateColAlias(this.form).then(response => {
            if (response.code === 0) {
              this.msgSuccess('修改成功')
              if (this.form.isDimension === '1') {
                this.openDetail = true
              }
              this.open = false
              this.getList()
            }
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: undefined,
        tablenameAliasId: undefined,
        columnName: undefined,
        dataType: undefined,
        columnDesc: undefined,
        columnAlias: undefined,
        isquota: undefined,
        isdimension: undefined,
        updateBy: Cookies.get('username')
      }
      this.resetForm('form')
    },
    changeDb(val) {
      this.loading = true
      listTableAlias({
        datasourceId: val,
        status: 1,
        current: 1,
        size: 1000,
        ascs: 'tableName, tableNameAlias'
      }).then(response => {
        this.tableList = response.data.records
        for (const t of this.tableList) {
          if (t.tableNameAlias === null) {
            t.tableNameAlias = t.tableName
          }
        }
        this.loading = false

      })
    },
    changeTable(val) {
      this.loading = true
      this.queryParams.tablenameAliasId = val
      this.getList()
      this.showSync = true
    },
    getList() {
      this.loading = true
      listColAlias(this.queryParams).then(response => {
        this.colList = response.data.records
        this.total = response.data.total
        this.loading = false

      })
    },
    handleQuotaChange(row) {
      this.row = row
      let text = row.isquota === '1' ? '启用' : '停用'
      this.reset()
      this.form = {
        id: row.id,
        isquota: row.isquota
      }
      if (row.isquota === '1') {
        this.resetQuota()
        if (row.columnAlias) {
          this.quotaForm.name = row.columnAlias
          this.readOnly = true
        } else {
          this.readOnly = false
        }
        this.openQuota = true

      } else {
        this.updateIsQuota(text)
      }

    },
    updateIsQuota(text) {
      updateColAlias(this.form).then(response => {
        if (response.code === 0) {
          this.msgSuccess(text + '成功')
        }
      })
    },
    handleDimChange(row) {
      let text = row.isdimension === '1' ? '启用' : '停用'
      this.reset()
      this.form = {
        id: row.id,
        isdimension: row.isdimension
      }
      updateColAlias(this.form).then(response => {
        if (response.code === 0) {
          this.msgSuccess(text + '成功')
          if (row.isdimension === '1') {
            this.openDetail = true
            this.colnameAliasId = row.id
            this.columnAlias = ''
          }
        }
      })
    },
    changeZone(val) {
      this.setLoading = true
      this.setList = []
      getThemeSetTree(val).then((response) => {
        this.setList = response.data
        this.setLoading = false

      }).catch(() => {
        this.msgSuccess('暂无数据')
      })
    },
    cancelQuota() {
      this.openQuota = false
      this.row.isquota = '0'
      this.resetQuota()
    },
    resetQuota() {
      this.quotaForm = {
        id: undefined,
        name: undefined,
        uname: undefined,
        description: undefined,
        type: '1',
        code: undefined,
        label: undefined,
        parentId: 0,
        // themeSetId: undefined,
        createBy: Cookies.get('username'),
        updateby: undefined,
        sType: '1',
        sTable: undefined,
        sCol: undefined
      }
      this.resetForm('quotaForm')
    },

    submitQuotaForm() {
      let tables = this.tableList.filter(table => table.id === this.queryParams.tablenameAliasId)
      this.quotaForm.code = this.row.columnName
      this.quotaForm.sTable = tables[0].tableName
      this.quotaForm.sCol = this.quotaForm.code
      this.quotaForm.datasourceId = this.datasourceId
      this.quotaForm.colnameId = this.row.id
      addQuota(this.quotaForm).then(response => {
        if (response.code === 0) {
          this.openQuota = false
          this.form.columnAlias = this.quotaForm.name
          this.updateIsQuota('启用')
        }
      })
    },
    handleInject() {
      console.log(this.queryParams.tablenameAliasId)
      injectQuotaValue({ tablenameAliasId: this.queryParams.tablenameAliasId }).then(response => {
        console.log(response)
        if (response.code === 0) {
          this.msgSuccess('注入成功')
        } else {
          this.msgSuccess(response.data)
        }
      })
    }
  }

}
</script>

<style scoped>

</style>
